//
//  RecommenViewController.m
//  Inner  Voice
//
//  Created by Martin.Wang on 16/2/27.
//  Copyright © 2016年 徐海宇. All rights reserved.
//

#import "RecommenViewController.h"


#define appDelegate ((AppDelegate *)[[UIApplication sharedApplication]delegate])

@interface RecommenViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@property (weak, nonatomic) IBOutlet RecommendTopView *hotView;

@property (nonatomic, strong) NSMutableArray *recommendSounds;

@property (nonatomic, assign) int page;

@property (nonatomic, strong) NSDictionary *homeHotSoundsDic;

@property (strong, nonatomic)UIButton *btn1;

@property (strong, nonatomic)UIButton *btn2;
@end

static NSString *kcellIdentifier = @"collectionCellID";
static NSString *kheaderIdentifier = @"ReusableView";
static NSString *hotheaderIdentifier = @"hotReusableView";
static NSString *hotReusabelheaderIdentifier = @"dayHotReusableView";
static NSString *hotcellIdentifier = @"hotCellID";

@implementation RecommenViewController

- (NSMutableArray*)recommendSounds{
    if (_recommendSounds == nil) {
        _recommendSounds = [NSMutableArray array];
    }
    return _recommendSounds;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   

    __weak typeof(self) tempself = self;
    
    if (self.hotView.hotBtn.selected == NO && self.hotView.recommendBtn.selected == NO) {
        
        self.hotView.recommendBtn  .selected = YES;
        
    }
    
    self.hotView.hotBtnAction = ^{
        
        [self.myCollectionView reloadData];
        
        if (!tempself.hotView.hotBtn.selected) {
            
            [tempself homeSoundRecommendWithPage:tempself.page];
            
        }else{
            
            [tempself homeHotSounds];
            
        }
        
        //[tempself.myCollectionView reloadData];
        
    };
    
    self.hotView.recommendBtnAction = ^{
        
        [self.myCollectionView reloadData];
        
        if (!tempself.hotView.hotBtn.selected) {
            
            [tempself homeSoundRecommendWithPage:tempself.page];
            
        }else{
            
            [tempself homeHotSounds];
            
        }
        
        //        [tempself.myCollectionView reloadData];
    };
    
    self.page = 1;
    
    self.myCollectionView.delegate = self;
    self.myCollectionView.dataSource = self;
    self.myCollectionView.showsVerticalScrollIndicator = NO;
    
    self.myCollectionView.mj_footer.automaticallyHidden = YES;
    // 下拉刷新
    self.myCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self xiahomeSoundRecommendWithPage];
        
    }];
    
    self.myCollectionView.mj_footer.automaticallyHidden = YES;
    
    [self homeSoundRecommendWithPage:self.page];
    
    // 上拉刷新
    self.myCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page++;
        
        [self homeSoundRecommendWithPage:self.page];
        
    }];
    
    //通过Nib生成cell，然后注册 Nib的view需要继承 UICollectionViewCell
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"myCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kcellIdentifier];
    
    //通过Nib生成cell，然后注册 Nib的view需要继承 UICollectionViewCell
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"DailyCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:hotcellIdentifier];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"topCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kheaderIdentifier];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"HotCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:hotheaderIdentifier];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self.myCollectionView registerNib:[UINib nibWithNibName:@"DayHotCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:hotReusabelheaderIdentifier];
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)homeHotSounds{

    NSString *url = @"http://1.wangtest11.applinzi.com/home/Banner/backhomeSoundHot";
    
    AFHTTPSessionManager *httpSession1 = [AFHTTPSessionManager manager];
    
    [httpSession1 GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"%@",responseObject);
        [self.recommendSounds removeAllObjects];
        
        NSDictionary *dic = responseObject;
        
        self.homeHotSoundsDic = dic[@"data"];
        
        self.page = 1;
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"ERROR %@",error);
        
    }];
    
}

- (void)xiahomeSoundRecommendWithPage{

    NSString *url = @"http://1.wangtest11.applinzi.com/home/Banner/backhomeSoundRecommend?page=1";
    
    AFHTTPSessionManager *httpSession1 = [AFHTTPSessionManager manager];
    
    [httpSession1 GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        [self.recommendSounds removeAllObjects];
        
        NSDictionary *dic = responseObject;
        
        NSArray *sounds = dic[@"data"];
        
        int a = (int)[sounds count];
        
        for (int b = 0; b < a; b++) {
            
            [self.recommendSounds addObject:sounds[b]];
            
        }
        
        self.page = 1;
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"ERROR %@",error);
        
    }];
    
}

- (void)homeSoundRecommendWithPage:(int)page{
    
    NSString *url = [NSString stringWithFormat:@"http://1.wangtest11.applinzi.com/home/Banner/backhomeSoundRecommend?page=%d",page];
    
    AFHTTPSessionManager *httpSession = [AFHTTPSessionManager manager];
    
    [httpSession GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSDictionary *dic = responseObject;
        
        NSArray *sounds = dic[@"data"];
        
//        //添加
//        [self.recommendSounds removeAllObjects];
        
        int a = (int)[sounds count];
        
        for (int b = 0; b < a; b++) {
            
            [self.recommendSounds addObject:sounds[b]];
            
        }
        
        [self.myCollectionView reloadData];
        
        [self.myCollectionView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"ERROR %@",error);
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if (self.hotView.hotBtn.selected) {
        
        if (indexPath.section == 0) {
            
            HotCollectionReusableView *view1 = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:hotheaderIdentifier forIndexPath:indexPath];
            
            view1.push = ^(NSDictionary *sound){
                
                NSLog(@"%@",sound);
                
                __weak typeof (self) temp = self;
                
                [temp playWithSound:sound];
                
            };
            
            return view1;
            
        }else if (indexPath.section == 1){
        
            DayHotCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:hotReusabelheaderIdentifier forIndexPath:indexPath];
            
            view.dayLabel.text = @"本周最热";
            
            return view;
        
        }else{
        
            DayHotCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:hotReusabelheaderIdentifier forIndexPath:indexPath];
            
            view.dayLabel.text = @"本月最热";
            
            return view;
        
        }
        
    }else{
    
    topCollectionReusableView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:kheaderIdentifier   forIndexPath:indexPath];
        
        view.push = ^(NSDictionary *sound){
        
            NSLog(@"%@",sound);
            
          __weak typeof (self) temp = self;
            
        [temp playWithSound:sound];
            
        };
        
    return view;

    }
    
}

#pragma mark -CollectionView datasource

#pragma mark - section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    if (self.hotView.hotBtn.selected) {
        return 3;
    }
    return 1;
}

#pragma mark - item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.hotView.hotBtn.selected) {
        return 10;
    }

    return self.recommendSounds.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.hotView.hotBtn.selected) {
        
        if (indexPath.section == 0) {
            
            //重用cell
            myCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcellIdentifier forIndexPath:indexPath];
            
            NSDictionary *sound = self.homeHotSoundsDic[@"daily"][indexPath.row];
            
            if (!sound) {
                return cell;
            }
            
            [cell loadImageWithStr:sound[@"pic_200"]];
            
            cell.soundName.text = sound[@"name"];
            
            return cell;
            
            
        }else if (indexPath.section == 1){
        
            //重用cell
            DailyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:hotcellIdentifier forIndexPath:indexPath];
            
            NSDictionary *sound = self.homeHotSoundsDic[@"weekly"][indexPath.row];
            
            if (!sound) {
                return cell;
            }
            
            [cell loadImageWithStr:sound[@"pic_200"]];
            
            cell.soundName.text = sound[@"name"];
            
            cell.soundInfo.text = sound[@"info"];
            
            cell.loveCount.text = sound[@"like_count"];
            
            return cell;
            
        }else{
        
            //重用cell
            DailyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:hotcellIdentifier forIndexPath:indexPath];
            
            NSDictionary *sound = self.homeHotSoundsDic[@"monthly"][indexPath.row];
            
            if (!sound) {
                return cell;
            }
            
            [cell loadImageWithStr:sound[@"pic_200"]];
            
            cell.soundName.text = sound[@"name"];
            
            cell.soundInfo.text = sound[@"info"];
            
            cell.loveCount.text = sound[@"like_count"];
            
            return cell;
            
        }
        
    }else{
    
    //重用cell
    myCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kcellIdentifier forIndexPath:indexPath];
    
    NSDictionary *sound = self.recommendSounds[indexPath.row];
    
        if (!sound) {
            return cell;
        }
        
    [cell loadImageWithStr:sound[@"pic_200"]];
    
    cell.soundName.text = sound[@"name"];
    
    return cell;
    
    }
}

#pragma mark - 定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.hotView.hotBtn.selected){
        
        if (indexPath.section == 0) {
            return CGSizeMake(self.view.frame.size.width/2.2, self.view.frame.size.height/5);
        }else{
            
            return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height/12);
        }
    }
    return CGSizeMake(self.view.frame.size.width/2.2, self.view.frame.size.height/5);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, self.view.frame.size.width/50, 10, self.view.frame.size.width/50);
}

#pragma mark - 选择播放歌曲
- (void)playWithSound:(NSDictionary*)sound{
    
    NSLog(@"%@",sound);
    
    [appDelegate.InPlayerViewController.inplayer stop];
    
    
    
    InSound *inSound = [[InSound alloc]init];
    
    inSound.inSound_icon = sound[@"pic_100"];
    inSound.inSound_name = sound[@"name"];
    inSound.inSound_Url = sound[@"source"];
    inSound.sound_id = sound[@"id"];
//    inSound.inSound_id = (NSInteger)sound[@"user_id"];
    
    [InSoundTool insertInToSound:inSound];//本地数据库插入播放过的歌曲
    
    [appDelegate.InPlayerViewController.inplayer playWithUrl:[NSURL URLWithString:sound[@"source"]] showView:appDelegate.InPlayerViewController.sliderView]; 
    
    //播放页面的歌曲信息里面的模型
    appDelegate.InPlayerViewController.inSound = inSound;
    
    NSMutableArray *playingArray = [InSoundTool soundArray];
    
    appDelegate.InPlayerViewController.playingSoundArray = playingArray;
    
    NSLog(@"%@",sound[@"source"]);
    
    InSoundTableViewController *controller = [[InSoundTableViewController alloc] init];
    
    __weak typeof (self) temp = self;
    
    controller.dic = sound;
    
    //push用在UINavigationController下得语句
    [temp.navigationController pushViewController:controller animated:YES];

    
    
}

#pragma mark - 选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.hotView.hotBtn.selected) {
        
        if (indexPath.section == 0) {
        
            NSDictionary *sound = self.homeHotSoundsDic[@"daily"][indexPath.row];
            
            if (!sound) {
                return;
            }
            
            [self playWithSound:sound];
       
            
        }else if (indexPath.section == 1){

            
            NSDictionary *sound = self.homeHotSoundsDic[@"weekly"][indexPath.row];
            
            if (!sound) {
                return;
            }
            
            [self playWithSound:sound];
            
        }else{

            
            NSDictionary *sound = self.homeHotSoundsDic[@"monthly"][indexPath.row];
            
            if (!sound) {
                return;
            }
            
            [self playWithSound:sound];
            
        }

    }else {
    
        NSDictionary *sound = self.recommendSounds[indexPath.row];
        
        if (!sound) {
            return;
        }
        
        [self playWithSound:sound];
        
        
    }
   
}
#pragma mark - 返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (self.hotView.hotBtn.selected) {
        
        if (section == 0) {
            CGSize size={self.view.frame.size.width,self.view.frame.size.height*0.22};
            return size;
        }else{
            CGSize size = {self.view.frame.size.width,self.view.frame.size.height*0.1};
            return size;
        }
        
    }else{
    
    CGSize size={self.view.frame.size.width,self.view.frame.size.height*0.22};
    return size;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
